package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.product.api.domain.Brand;
import com.spzx.product.domain.CategoryBrand;
import com.spzx.product.mapper.CategoryBrandMapper;
import com.spzx.product.service.ICategoryBrandService;
import com.spzx.product.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryBrandImpl extends ServiceImpl<CategoryBrandMapper, CategoryBrand> implements ICategoryBrandService {
    @Autowired
    private  CategoryBrandMapper categoryBrandMapper;

    @Autowired
    private ICategoryService categoryService;

    /**
     * 分类品牌Service业务层处理
     */
    @Override
    public List<CategoryBrand> selectCategoryBrandList(CategoryBrand categoryBrand) {

        return categoryBrandMapper. selectCategoryBrandList(categoryBrand);
    }

    @Override
    public CategoryBrand getCategoryBrandInfo(Long id) {
        CategoryBrand categoryBrand = this.categoryBrandMapper.selectById(id);
        //三级分类下拉需要回显，只返回第三级分类id是不能回显三个级别的分类的。必须将三个级别分类id都返回才能正常回显。
        //三个级别的id必须按照顺序返回:【一级id,二级id,三级id】    例如:[1.2.3]

        //根据指定分类id,查找当前分类id,以及全部祖先id
        List<Long> categoryIdList=categoryService.getAllCategoryIdList(categoryBrand.getCategoryId());
        categoryBrand.setCategoryIdList(categoryIdList);
        return categoryBrand;
    }

    //新增分类品牌
    @Override
    public int insertCategoryBrand(CategoryBrand categoryBrand) {
        Long count = categoryBrandMapper.selectCount(new LambdaQueryWrapper<CategoryBrand>().eq(CategoryBrand::getBrandId, categoryBrand.getBrandId())
                .eq(CategoryBrand::getCategoryId, categoryBrand.getCategoryId()));
        if (count>0){
            throw new ServiceException("数据已经存在");
        }
        return categoryBrandMapper.insert(categoryBrand);
    }

    //修改
    @Override
    public int updateCategoryBrand(CategoryBrand categoryBrand) {
        CategoryBrand categoryBrandInfo = categoryBrandMapper.selectOne(new LambdaQueryWrapper<CategoryBrand>().eq(CategoryBrand::getBrandId, categoryBrand.getBrandId())
                .eq(CategoryBrand::getCategoryId, categoryBrand.getCategoryId()));
        if (categoryBrandInfo !=null  && categoryBrand.getId().intValue() != categoryBrandInfo.getId().intValue()){
            throw new ServiceException("数据已经存在");
        }
        return categoryBrandMapper.updateById(categoryBrand);
    }

    //根据分类id获取品牌列表
    @Override
    public List<Brand> getBrandListByCategoryId(Long categoryId) {
        return categoryBrandMapper. getBrandListByCategoryId(categoryId);
    }
}
